// https://leetcode.cn/problems/maximum-sum-circular-subarray/description/?envType=study-plan-v2&envId=top-interview-150

class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int curMax = nums[0], nonCircleMax = nums[0];
        int totalSum = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            curMax = max(curMax + nums[i], nums[i]);
            nonCircleMax = max(curMax, nonCircleMax);
            totalSum += nums[i];
        }

        int curMin = nums[0], globalMin = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            curMin = min(curMin + nums[i], nums[i]);
            globalMin = min(curMin, globalMin);
        }

        int circleMax = totalSum - globalMin;
        
        if (circleMax == 0 && nonCircleMax < 0) {
            return nonCircleMax;
        }
        return max(circleMax, nonCircleMax);
    }
};